import 'package:get/get.dart';

import '../../services/database_service.dart';
import '../../services/tianyi_cloud_service.dart';
import '../../services/file_manager_service.dart';
import '../../services/notification_service.dart';
import '../../services/preferences_service.dart';
import '../../services/sync_service.dart';
import '../../services/upload/upload_service.dart';
import '../../services/download/download_service.dart';
import '../controllers/main_controller.dart';
import '../controllers/file_controller.dart';
import '../controllers/upload_controller.dart';
import '../controllers/download_controller.dart';
import '../controllers/search_controller.dart';
import '../controllers/settings_controller.dart';

class InitialBinding extends Bindings {
  @override
  void dependencies() {
    // 核心服务 - 按依赖顺序注入
    
    // 1. 首先注入偏好设置服务（其他服务可能依赖它）
    Get.put<PreferencesService>(
      PreferencesService(),
      permanent: true,
    );
    
    // 2. 数据库服务
    Get.put<DatabaseService>(
      DatabaseService(),
      permanent: true,
    );
    
    // 3. 通知服务
    Get.put<NotificationService>(
      NotificationService(),
      permanent: true,
    );
    
    // 4. 云服务
    Get.put<TianyiCloudService>(
      TianyiCloudService(),
      permanent: true,
    );
    
    // 5. 文件管理服务
    Get.put<FileManagerService>(
      FileManagerService(),
      permanent: true,
    );
    
    // 6. 上传服务
    Get.put<UploadService>(
      UploadService(),
      permanent: true,
    );
    
    // 7. 下载服务
    Get.put<DownloadService>(
      DownloadService(),
      permanent: true,
    );
    
    // 8. 同步服务（依赖上传和下载服务）
    Get.put<SyncService>(
      SyncService(),
      permanent: true,
    );
    
    // 控制器 - 在服务之后注入
    
    // 主控制器
    Get.put<MainController>(
      MainController(),
      permanent: true,
    );
    
    // 文件控制器
    Get.put<FileController>(
      FileController(),
      permanent: true,
    );
    
    // 上传控制器
    Get.put<UploadController>(
      UploadController(),
      permanent: true,
    );
    
    // 下载控制器
    Get.put<DownloadController>(
      DownloadController(),
      permanent: true,
    );
    
    // 搜索控制器
    Get.put<SearchController>(
      SearchController(),
      permanent: true,
    );
    
    // 设置控制器
    Get.put<SettingsController>(
      SettingsController(),
      permanent: true,
    );
  }
  
  /// 初始化所有服务
  /// 在应用启动时调用，确保所有服务都正确初始化
  static Future<void> initializeServices() async {
    try {
      // 获取所有服务实例
      final preferencesService = Get.find<PreferencesService>();
      final databaseService = Get.find<DatabaseService>();
      final notificationService = Get.find<NotificationService>();
      final cloudService = Get.find<TianyiCloudService>();
      final fileManagerService = Get.find<FileManagerService>();
      final uploadService = Get.find<UploadService>();
      final downloadService = Get.find<DownloadService>();
      final syncService = Get.find<SyncService>();
      
      // 按顺序初始化服务
      print('正在初始化偏好设置服务...');
      await preferencesService.init();
      
      print('正在初始化数据库服务...');
      await databaseService.init();
      
      print('正在初始化通知服务...');
      await notificationService.init();
      
      print('正在初始化云服务...');
      await cloudService.init();
      
      print('正在初始化文件管理服务...');
      await fileManagerService.init();
      
      print('正在初始化上传服务...');
      await uploadService.init();
      
      print('正在初始化下载服务...');
      await downloadService.init();
      
      print('正在初始化同步服务...');
      await syncService.init();
      
      print('所有服务初始化完成');
      
    } catch (e) {
      print('服务初始化失败: $e');
      rethrow;
    }
  }
  
  /// 清理所有服务
  /// 在应用关闭时调用
  static Future<void> disposeServices() async {
    try {
      // 按相反顺序清理服务
      final syncService = Get.find<SyncService>();
      final downloadService = Get.find<DownloadService>();
      final uploadService = Get.find<UploadService>();
      final fileManagerService = Get.find<FileManagerService>();
      final cloudService = Get.find<TianyiCloudService>();
      final notificationService = Get.find<NotificationService>();
      final databaseService = Get.find<DatabaseService>();
      final preferencesService = Get.find<PreferencesService>();
      
      print('正在清理同步服务...');
      await syncService.dispose();
      
      print('正在清理下载服务...');
      await downloadService.dispose();
      
      print('正在清理上传服务...');
      await uploadService.dispose();
      
      print('正在清理文件管理服务...');
      await fileManagerService.dispose();
      
      print('正在清理云服务...');
      await cloudService.dispose();
      
      print('正在清理通知服务...');
      await notificationService.dispose();
      
      print('正在清理数据库服务...');
      await databaseService.dispose();
      
      print('正在清理偏好设置服务...');
      await preferencesService.dispose();
      
      print('所有服务清理完成');
      
    } catch (e) {
      print('服务清理失败: $e');
    }
  }
  
  /// 重启所有服务
  /// 在需要重新初始化时调用
  static Future<void> restartServices() async {
    await disposeServices();
    await initializeServices();
  }
  
  /// 检查服务健康状态
  static Map<String, bool> checkServicesHealth() {
    final health = <String, bool>{};
    
    try {
      health['PreferencesService'] = Get.isRegistered<PreferencesService>();
      health['DatabaseService'] = Get.isRegistered<DatabaseService>();
      health['NotificationService'] = Get.isRegistered<NotificationService>();
      health['TianyiCloudService'] = Get.isRegistered<TianyiCloudService>();
      health['FileManagerService'] = Get.isRegistered<FileManagerService>();
      health['UploadService'] = Get.isRegistered<UploadService>();
      health['DownloadService'] = Get.isRegistered<DownloadService>();
      health['SyncService'] = Get.isRegistered<SyncService>();
      health['MainController'] = Get.isRegistered<MainController>();
      health['FileController'] = Get.isRegistered<FileController>();
      health['UploadController'] = Get.isRegistered<UploadController>();
      health['DownloadController'] = Get.isRegistered<DownloadController>();
      health['SearchController'] = Get.isRegistered<SearchController>();
      health['SettingsController'] = Get.isRegistered<SettingsController>();
    } catch (e) {
      print('检查服务健康状态失败: $e');
    }
    
    return health;
  }
  
  /// 获取服务统计信息
  static Map<String, dynamic> getServicesStatistics() {
    final stats = <String, dynamic>{};
    
    try {
      // 获取各个服务的统计信息
      if (Get.isRegistered<UploadService>()) {
        final uploadService = Get.find<UploadService>();
        stats['upload'] = uploadService.getStatistics();
      }
      
      if (Get.isRegistered<DownloadService>()) {
        final downloadService = Get.find<DownloadService>();
        stats['download'] = downloadService.getStatistics();
      }
      
      if (Get.isRegistered<SyncService>()) {
        final syncService = Get.find<SyncService>();
        stats['sync'] = {
          'status': syncService.syncStatus.toString(),
          'is_syncing': syncService.isSyncing,
          'last_sync_time': syncService.lastSyncTime?.toIso8601String(),
        };
      }
      
      if (Get.isRegistered<FileManagerService>()) {
        final fileManagerService = Get.find<FileManagerService>();
        stats['file_manager'] = {
          'current_path': fileManagerService.currentPath,
          'files_count': fileManagerService.currentFiles.length,
          'selected_count': fileManagerService.selectedFiles.length,
        };
      }
      
      if (Get.isRegistered<TianyiCloudService>()) {
        final cloudService = Get.find<TianyiCloudService>();
        stats['cloud'] = {
          'is_logged_in': cloudService.isLoggedIn,
          'current_user': cloudService.currentUser?.nickname,
        };
      }
      
    } catch (e) {
      print('获取服务统计信息失败: $e');
    }
    
    return stats;
  }
}